﻿using System;
using System.Threading;
using System.Windows;
using Microsoft.Phone.Shell;
using TradeMeSDK.OAuthLibrary;

namespace TradeMeSDK
{
    public static class TradeMeDispatcher
    {
        private static Action<Action> _executor = action => action();

        /// <summary>
        /// Initializes the framework using the current dispatcher.
        /// </summary>
        public static void Initialize()
        {
#if SILVERLIGHT
            var dispatcher = Deployment.Current.Dispatcher;
#else
            var dispatcher = Dispatcher.CurrentDispatcher;
#endif
            _executor = action =>{
                if(dispatcher.CheckAccess())
                    action();
                else dispatcher.BeginInvoke(action);
            };

#if WINDOWS_PHONE
            PhoneApplicationService.Current.Deactivated += Current_Deactivated;
            PhoneApplicationService.Current.Activated += Current_Activated;
#endif
        }

#if WINDOWS_PHONE

        static void Current_Deactivated(object sender, DeactivatedEventArgs e)
        {
            // Store OAuth data so the user does not have to login again
            var store = new TransientDataStore();
            store.Backup(TradeMeConstants.TradeMeToken, TradeMeOAuth.Token);
            store.Backup(TradeMeConstants.TradeMeTokenSecret, TradeMeOAuth.TokenSecret);
            store.Backup(TradeMeConstants.TradeMeVerifier, TradeMeOAuth.Verifier);
        }

        static void Current_Activated(object sender, ActivatedEventArgs e)
        {
            var store = new TransientDataStore();
            TradeMeOAuth.Token = store.Restore<string>(TradeMeConstants.TradeMeToken);
            TradeMeOAuth.TokenSecret = store.Restore<string>(TradeMeConstants.TradeMeTokenSecret);
            TradeMeOAuth.Verifier = store.Restore<string>(TradeMeConstants.TradeMeVerifier);
        }

#endif

        /// <summary>
        /// Executes the action on the UI thread.
        /// </summary>
        /// <param name="action">The action to execute.</param>
        public static void OnUIThread(this Action action)
        {
            if (action != null)
                _executor(action);
        }

        public static void OnUIThread(int delayMilliSeconds, Action action)
        {
            ThreadPool.QueueUserWorkItem(state =>
            {
                Thread.Sleep(delayMilliSeconds);
                OnUIThread(action);
            });
        }

    }

}
